package org.dizena.common.trace.httpclient.handler;

import org.dizena.common.base.enums.EnumHeaderKey;
import org.dizena.common.base.enums.EnumLogLevel;
import org.dizena.common.logger.bean.LogInfo;
import org.dizena.common.logger.bean.LogRpcEvent;
import org.dizena.common.utils.ReqUtil;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;

public class HttpClientResponseErrorHandler implements ResponseErrorHandler {

    private ApplicationEventPublisher publisher;

    public HttpClientResponseErrorHandler(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        return response.getStatusCode().isError();
    }

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        LogInfo logInfo = new LogInfo();
        logInfo.setTraceId(ReqUtil.getTrace());
        logInfo.setClientIp(ReqUtil.getAllHeaderMap().get(EnumHeaderKey.REQUEST_IP));
        logInfo.setResponseTime(System.currentTimeMillis());
        try {
            String error = new String(StreamUtils.copyToByteArray(response.getBody()));
            logInfo.setException(response.getRawStatusCode() + " " + response.getStatusText() + " " + error);
        } catch (IOException e) {
            logInfo.setException(response.getRawStatusCode() + " " + response.getStatusText());
        }
        publisher.publishEvent(new LogRpcEvent(this, logInfo, EnumLogLevel.ERROR));
    }
}
